package com.it.service.impl;

import com.it.entity.SysUser;
import com.it.service.SysMenuService;
import com.it.service.SysUserService;
import com.it.vo.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: CaoYouGen
 * @DateTime: 2023/11/09/10:20
 * @注释: TODO
 **/
@Service
public class SecurityUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getUserName(username);
        // 判断对象是否为空
        if (ObjectUtils.isEmpty(sysUser)){
            throw new UsernameNotFoundException("该用户不存在！");
        }
        // 判断用户是否可用
        if (!sysUser.getAccountNoExpired().equals(1)) {
            throw new UsernameNotFoundException("该账户已过期！");
        }
        // 通过用户id获取用户的所有权限
        List<String> permissions = sysMenuService.queryPermissionsByUserId(sysUser.getUserId());

        // 使用Stream流将 List<String> permissions 转换为 List<SimpleGrantedAuthority> grantedAuthorities
        List<SimpleGrantedAuthority> grantedAuthorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        // 创建一个用户权限对象
        SecurityUser securityUser = new SecurityUser(sysUser);
        // 将权限设置到用户对象中
        securityUser.setSimpleGrantedAuthorities(grantedAuthorities);
        // 返回
        return securityUser;
    }
}
